package com.gitee.hermer.engine.jars.dependent.dubbo.configuration;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.gitee.hermer.boot.jee.commons.reflect.ClassUtils;
import com.gitee.hermer.boot.jee.commons.verify.Assert;
import com.gitee.hermer.engine.jars.core.domain.EngineConstant;
import com.gitee.hermer.engine.jars.dependent.dubbo.config.DubboProperties;
import com.gitee.hermer.engine.jars.dependent.zkclient.config.ZkClientProperties;
import com.gitee.hermer.engine.jars.dependent.zkclient.configuration.ZkClientAutoConfiguration;

@Configuration
@Import(value={
		DubboRegistryAutoConfiguration.class,
		DubboServiceAutoConfiguration.class,
		DubboClientAutoConfiguration.class
})
public class DubboAutoConfiguration implements Ordered{

	@Bean
	public DubboProperties dubboProperties(){
		return new DubboProperties();
	}

	@Bean
	@Autowired
	public ApplicationConfig application(DubboProperties properties,ZkClientProperties clientProperties,RegistryConfig registryConfig) {
		Assert.hasText(properties.getAppName());
		if(!ClassUtils.isAssignable(EngineConstant.CLASS_ENGINE_APP_CLASS_LOADER, Thread.currentThread().getContextClassLoader().getClass())){
			System.setProperty(EngineConstant.PROPERTIES_VALUE_KEY_DUBBO_APPLICATION_NAME, properties.getAppName());
			System.setProperty(EngineConstant.PROPERTIES_VALUE_KEY_DUBBO_REGISTRY_ADDRESS, clientProperties.getResAddress());
		}
		ApplicationConfig applicationConfig = new ApplicationConfig(properties.getAppName());
		applicationConfig.setRegistry(registryConfig);
		return applicationConfig;
	}
	@Override
	public int getOrder() {
		return HIGHEST_PRECEDENCE+1000;
	}


}
